<template>
	<view class="appointmentRegistration">
		<div class="title" @click="comeBack()">
			<image src="../../static/icon_arrow_blue_left.png"></image>
			请选择挂号科室
		</div>
		<div>
			<uni-notice-bar showIcon scrollable background-color="rgba(47,89,243,0.5)" color="#fff" :text="tips" :speed="100" />
		</div>
		<uni-collapse accordion>
			<uni-collapse-item style="font-size: 28px;" v-for="items in departmentList" :title="items.MC"
				@click="expandDepartment(items['ID'])">
				<div style="font-size: 16px;color: #666;padding: 10px 0 10px 16px;">该科室挂号时间为：{{ items.openTime }}</div>
				<div class="departmentInfo">
					<div class="prompt">请选择挂号日期</div>
					<div class="data" v-for="dayList in recentSevenDays" @click="selectedTheDate(dayList,items['ID'])"
						:style="{'color': dayList['monthDay']==selectedDate?'#00baff':null}">
						<div>{{ dayList['monthDay'] }}</div>
						<div>{{ dayList['week'] }}</div>
					</div>
					<view class="prompt">
						请选择挂号时间：<span class="uni-list-cell-db">
							<picker style="display: inline-block;" mode="time" :value="times" start="09:01" end="21:01"
								@change="bindTimeChange">
								<view class="uni-input">{{times}}</view>
							</picker>
						</span>
					</view>

					<div class="registered">
						<div class="list" v-for="list in registered" @click="registeredConfirm(list)">
							<image src="../../static/doctor_icon.jpeg"></image>
							<div class="registered_info">
								<div>{{list["KSMC"]}}</div>
								<div>{{list["XMMC"]}}</div>
								<div>挂号金额:{{list["PRICE"]}}</div>
								<div v-if="parseFloat(list['SYHS']) > 0">剩余号源:{{list['SYHS']}}</div>
							</div>
							<div class="registered_click">
								{{parseFloat(list['SYHS']).toString() !== "NaN"  && parseFloat(list['SYHS']) > 0?"预约":"无号"}}
							</div>
						</div>
					</div>
				</div>
			</uni-collapse-item>

		</uni-collapse>
	</view>
</template>

<script lang="ts">
	import { globalVariable } from '../../globalVariable/globalVariable';
	import { request } from '../../Providing/request'
	import { uiCollection } from '../../Providing/uiCollection';

	export default {
		data() {
			return {
				tips: '妇科门诊、计划生育门诊、更年期门诊挂号请挂妇女保健计划生育技术服务部的号',
				departmentList: [],
				recentSevenDays: [],
				selectedDate: "",
				lastTimeRequestDepartmentId: "",
				time: "",
				registered: [],
				times: uiCollection.getDate('hour'),
			};
		},
		methods: {
			getDepartmentList() {
				new request().getDepartmentQuery().then((res) => {
					console.log("打印1", this.departmentList);
					this.departmentList = res['KSLIST']['KS'];
					//时间添加
					for (let i = 0; i < this.departmentList.length; i++) {
						if(this.departmentList[i].ID == 204) {
							this.$set(this.departmentList[i],'openTime','全天')
						}else if(this.departmentList[i].ID == 136) {
							this.$set(this.departmentList[i],'openTime','17:30-08:30')
						}else {
							this.$set(this.departmentList[i],'openTime','08:30-17:30')
						}
					}
					console.log("打印", this.departmentList);
				});
			},
			expandDepartment(id) {

				if (this.lastTimeRequestDepartmentId == id) {
					return false;
				}

				this.lastTimeRequestDepartmentId = id;
				this.selectedDate = this.recentSevenDays[0]['monthDay'];
				this.time = this.recentSevenDays[0]['date'];
				console.log('展开的科室ID', id);
				console.log('选中的日期', this.time);
				this.postNumberSourceQuery();
			},
			selectedTheDate(day, id) {
				if (this.selectedDate == day['monthDay'] && this.lastTimeRequestDepartmentId == id) {
					return false;
				}

				this.selectedDate = day['monthDay'];
				this.time = day['date']
				console.log("this.selectedDate", this.selectedDate, this.time);
				this.postNumberSourceQuery()
			},
			getRecentSevenDays() {
				for (let i = 0; i < 7; i++) {
					let day = uiCollection.getDay(i).split('|');
					this.recentSevenDays.push({ week: day[1], monthDay: day[0].slice(5), date: day[0] });
				}

				console.log(this.recentSevenDays);
			},
			postNumberSourceQuery() {
				this.registered = [];
				new request().postNumberSourceQuery(this.time + " 00:00:00", this.lastTimeRequestDepartmentId).then((res) => {
					console.log("获取科室挂号列表成功", res);
					if (res['type'] == "object") {
						this.registered.push(res['data']['GROUP']['HBLIST']['HB']);
					}

					if (res['type'] == "Array") {
						this.registered = res['data']['GROUP']['HBLIST']['HB'];
					}

					this.registered.forEach((item, index) => {
						console.log('打印item', item['PRICE'])
						if (item['PRICE'].substring(0, 1) == ".") {
							this.registered[index]['PRICE'] = "0" + item['PRICE']
						}
					})

					console.log("打印registered", this.registered);
				}).catch((err) => {
					console.log("获取科室挂号列表失败", err);
					uiCollection.showToast("获取挂号科室列表失败")
				})
			},
			registeredConfirm(department) {
				// 当前时间戳
				let timestamp = new Date().getTime()
				let currentS = (this.time + " " + this.times + ":" + "00")
				let timeS = Date.parse(currentS)
				if(timestamp > timeS) {
					uni.showModal({
						title: '提示',
						content: '请选择正确时间',
						showCancel: true,
						mask: true
					})
				}else {
					let second = this.toSecond(this.times + ":" + "00")
					if(department['KSID'] == 136) {
						let start = this.toSecond('17:30:00')
						let center = this.toSecond('24:00:00')
						let end = this.toSecond('08:30:00')
						if(second >= start && second <= center || second <= end) {
							this.requestConfirm(department)
						}else {
							uni.showModal({
								title: '提示',
								content: '该时间不能预约',
								showCancel: true,
								mask: true
							})
						}
					}else if(department['KSID'] == 204) {
						this.requestConfirm(department)
					}else {
						let start2 = this.toSecond('08:30:00')
						let end2 = this.toSecond('17:30:00')
						// let final = (center - start) + end
						if(second >= start2 && second <= end2) {
							this.requestConfirm(department)
						}else {
							uni.showModal({
								title: '提示',
								content: '该时间不能预约',
								showCancel: true,
								mask: true
							})
						}
					}
				}
			},
			requestConfirm(department) {
				if (parseFloat(department['SYHS']).toString() !== "NaN" && parseFloat(department['SYHS']) > 0) {
					console.log("挂号科室信息", department);
					let msg = "科室名称：" + department['KSMC'] + "\n"
						+ "挂号金额：" + department['PRICE'] + "\n"
						+ "时间：" + this.time + " " + this.times;
					console.log(msg)
					uiCollection.showModal(msg).then((res) => {
						if (res) {
							let data = {
								"hm": department['HM'],
								"type": 1,
								"appointTime": this.time + " " + this.times,
								"patientId": globalVariable.brid,
								"depId": this.lastTimeRequestDepartmentId,
								"price": department['PRICE'],
								"cardId": globalVariable.cardId,
								"xmid": department['XMID'],
								"depName": department["KSMC"],
								"regType": department["XMMC"]
							}

							new request().postApprequestLockSource(data).then((res) => {
								console.log("锁号成功返回信息", res)
								let order = { "regID": res['id'], "type": 1 }
								new request().postRegisteredOrder(order).then((res1 : string) => {
									globalVariable.qrCodePay.url = res1;
									globalVariable.qrCodePay.type = "挂号"
									globalVariable.qrCodePay.amount = department['PRICE']
									globalVariable.qrCodePay.payId = res['id']

									uni.$emit("goToQrCodePay");
								})
							}).catch((err) => {
								uiCollection.showToast("挂号锁定号源失败：" + err)
							})
						}
					})
				} else {
					uiCollection.showToast("该科室无可挂号源")
				}
			},
			toSecond(time) {
				let hour = time.split(':')[0];
				let min = time.split(':')[1];
				let sec = time.split(':')[2];
				
				let s = Number(hour*3600) + Number(min*60) + Number(sec);
				return s
			},
			bindTimeChange: function (e) {
				this.times = e.detail.value
			},
			comeBack() {
				uni.$emit("goToMenuList")
			}
		},
		created() {
			this.getDepartmentList();
			this.getRecentSevenDays();


		}
	}
</script>

<style lang="scss">
	.appointmentRegistration {
		height: 800px;

		.title {
			width: 100%;
			height: 40px;
			line-height: 40px;
			margin-left: 10px;
			color: #2f59f3;
			letter-spacing: 25px;
			text-indent: 10px;
			margin: auto;
			padding-left: 20px;
			background-color: #fff;

			image {
				width: 15px;
				height: 30px;
				top: 5px;
				float: left;


			}
		}

		.departmentInfo {
			width: 100%;
			min-width: 400px;
			height: 270px;

			.prompt {
				text-indent: 12px;
				font-size: 20px;
				line-height: 30px;
				// color:#00baff
			}

			.data {
				width: 100px;
				height: 60px;
				line-height: 25px;
				display: inline-block;
				text-align: center;
				border: 0.5px solid #99999921;
			}

			.registered {
				display: flex;
				flex-wrap: wrap;

				.list {
					margin: 10px;
					width: 330px;
					height: 115px;
					display: flex;
					text-align: center;
					border-radius: 200px;
					border: 1px solid #5883eb;

					div {

						text-align: center;
						line-height: 30px;
						font-size: 15px;
						overflow: hidden;
						text-overflow: ellipsis;
						white-space: nowrap;
					}

					;

					.registered_info {
						width: 55%;
					}

					.registered_click {
						line-height: 100px;
						flex: 1;
					}

					image {
						width: 115px;
						height: 115px;
						display: inline-block;
						overflow: hidden;
						position: relative;
						border-radius: 50%;
					}
				}
			}
		}

		.uni-collapse-item__title-text {
			font-size: 24px;
		}
	}
</style>